package com.himiotech.core.project.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.himiotech.core.framework.helper.constant.UserConstants;
import com.himiotech.core.framework.helper.exception.HimioException;
import com.himiotech.core.project.data.mapper.DictDataMapper;
import com.himiotech.core.project.data.mapper.DictTypeMapper;
import com.himiotech.core.project.helper.utils.DictUtils;
import com.himiotech.core.project.model.entity.dict.DictData;
import com.himiotech.core.project.model.entity.dict.DictType;
import com.himiotech.core.project.model.metadata.DictTypeMetadata;
import com.himiotech.core.project.service.IDictTypeService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 字典 业务层处理
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DictTypeServiceImpl extends ServiceImpl<DictTypeMapper, DictType> implements IDictTypeService {

    @Autowired
    private DictTypeMapper dictTypeMapper;

    @Autowired
    private DictDataMapper dictDataMapper;


    /**
     * 根据条件分页查询字典类型
     *
     * @param page     分页信息
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public Page<DictType> selectDictTypeListPage(Page<DictType> page, DictType dictType) {
        QueryWrapper<DictType> query = Wrappers.query();
        Map<String, Object> searchParams = dictType.getSearchParams();
        query.like(ObjectUtil.isNotEmpty(dictType.getDictName()), DictTypeMetadata.DICT_NAME.getColName(), dictType.getDictName());
        query.like(ObjectUtil.isNotEmpty(dictType.getDictType()), DictTypeMetadata.DICT_TYPE.getColName(), dictType.getDictType());
        query.eq(ObjectUtil.isNotEmpty(dictType.getStatus()), DictTypeMetadata.STATUS.getColName(), dictType.getStatus());

        if (!searchParams.isEmpty()) {
            String start = MapUtil.getStr(searchParams, StrUtil.toCamelCase(DictTypeMetadata.GMT_CREATE.getColName()).concat("Start")).concat(" 00:00:00");
            query.ge(StrUtil.isNotEmpty(start), DictTypeMetadata.GMT_CREATE.getColName(), start);
            String end = MapUtil.getStr(searchParams, StrUtil.toCamelCase(DictTypeMetadata.GMT_CREATE.getColName()).concat("End")).concat(" 23:59:59");
            query.le(StrUtil.isNotEmpty(start), DictTypeMetadata.GMT_CREATE.getColName(), end);
        }
        page = dictTypeMapper.selectPage(page, query);
        return page;
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<DictData> selectDictDataByType(String dictType) {
        List<DictData> dictDataList = DictUtils.getDictCache(dictType);
        if (CollectionUtils.isNotEmpty(dictDataList)) {
            return dictDataList;
        }
        dictDataList = dictDataMapper.selectDictDataByType(dictType);
        if (CollectionUtils.isNotEmpty(dictDataList)) {
            DictUtils.setDictCache(dictType, dictDataList);
            return dictDataList;
        }
        return null;
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public DictType selectDictTypeByType(String dictType) {
        return dictTypeMapper.selectOne(
                Wrappers.<DictType>query().eq(DictTypeMetadata.DICT_TYPE.getColName(), dictType));
    }

    /**
     * 批量删除字典类型
     *
     * @param ids 需要删除的数据
     */
    @Override
    public void deleteDictTypeByIds(String ids) {
        Long[] dictIds = Convert.toLongArray(ids.split(","));
        for (Long dictId : dictIds) {
            DictType dictType = this.getById(dictId);
            if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) {
                throw new HimioException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            dictTypeMapper.deleteById(dictId);
            DictUtils.removeDictCache(dictType.getDictType());
        }
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        List<DictType> dictTypeList = dictTypeMapper.selectList(Wrappers.emptyWrapper());
        for (DictType dict : dictTypeList) {
            List<DictData> dictDataList = dictDataMapper.selectDictDataByType(dict.getDictType());
            DictUtils.setDictCache(dict.getDictType(), dictDataList);
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache() {
        DictUtils.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache()
    {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(DictType dictType) {
        int row = dictTypeMapper.insert(dictType);
        if (row > 0) {
            DictUtils.setDictCache(dictType.getDictType(), null);
        }
        return row;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    public int updateDictType(DictType dictType) {
        DictType oldDict = dictTypeMapper.selectById(dictType.getDictId());
        dictDataMapper.updateDictDataType(oldDict.getDictType(), dictType.getDictType());
        int row = dictTypeMapper.updateById(dictType);
        if (row > 0) {
            List<DictData> dictDatas = dictDataMapper.selectDictDataByType(dictType.getDictType());
            DictUtils.setDictCache(dictType.getDictType(), dictDatas);        }
        return row;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(DictType dict) {
        long dictId = dict.getDictId() == null ? -1L : dict.getDictId();
        DictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType());
        if (dictType != null && dictType.getDictId() != dictId) {
            return UserConstants.DICT_TYPE_NOT_UNIQUE;
        }
        return UserConstants.DICT_TYPE_UNIQUE;
    }

}
